package com.zwcl.common.core.aspect;

import com.zwcl.common.core.annotation.EnumValid;
import com.zwcl.common.core.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;

/**
 * @Description 枚举自定义校验注解
 * @Author xyp
 * @Date 2020/5/19 16:45
 * @Email kunye.guo@wetax.com.cn
 */
@Slf4j
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {

    private Class<?> type;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        type = constraintAnnotation.type();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(null == value) {
            return true;
        }

        try {
            Method method = type.getMethod("isExist", value.getClass());
            Boolean isExist = (Boolean) method.invoke(null, value);
            return isExist;
        } catch (NoSuchMethodException e) {
            throw new BaseException("枚举类缺少isExist方法");
        } catch (Exception e) {
            log.error("枚举自定义校验注解异常", e);
            return false;
        }

    }

}
